package com.yishu.servlet;

import com.yishu.entity.Admin;
import com.yishu.Dao.AdminDao;
import com.yishu.util.DBConnection;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Connection;

public class LoginAdminServlet extends HttpServlet {

    AdminDao adminDao = new AdminDao();
    DBConnection dbConnection = new DBConnection();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        String adminName = req.getParameter("adminName");
        String password = req.getParameter("password");

        Admin admin = new Admin();
        admin.setAdminName(adminName);
        admin.setPassword(password);

        try {
            Connection connection = dbConnection.getCon();
            Admin currentAdmin = adminDao.adminLogin(connection,admin);
            dbConnection.closeCon(connection);

            if(currentAdmin != null) {
                session.setAttribute("adminName",adminName);
                req.getRequestDispatcher("/admin/adminCenter.jsp").forward(req,resp);
            }else {
                req.setAttribute("result","登录失败，账号或密码错误");
                req.getRequestDispatcher("/adminLogin.jsp").forward(req,resp);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
